<template>
  <div class="app-container">
          <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="题库名称" prop="name">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入题库名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="题库类型" prop="type">
          <el-select v-model="queryParams.type" placeholder="请选择题库类型" clearable>
            <el-option
              v-for="dict in (dict.type && dict.type.type) || []"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input-number v-model="queryParams.price" :min="0" :precision="2" :step="0.1" placeholder="按价格精确查询" />
        </el-form-item>
        <el-form-item label="所属科目" prop="subjectId">
          <el-select v-model="queryParams.subjectId" placeholder="请选择所属科目" clearable @change="handleSubjectChange">
            <el-option
              v-for="subject in subjectList || []"
              :key="subject.id"
              :label="subject.name"
              :value="subject.id"
            />
          </el-select>
        </el-form-item>
            <el-form-item label="所属课程" prop="courseId">
              <el-select v-model="queryParams.courseId" placeholder="请选择所属课程" clearable @change="handleCourseChange">
                <el-option
                  v-for="course in courseList || []"
                  :key="course.id"
                  :label="course.name"
                  :value="course.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="所属章节" prop="chapterId">
              <el-select v-model="queryParams.chapterId" placeholder="请选择所属章节" clearable @change="handleChapterChange">
                <el-option
                  v-for="chapter in chapterList || []"
                  :key="chapter.id"
                  :label="chapter.name"
                  :value="chapter.id"
                />
              </el-select>
            </el-form-item>
      <el-form-item label="状态" prop="del">
        <el-select v-model="queryParams.del" placeholder="请选择状态" clearable>
          <el-option label="全部" :value="null" />
          <el-option label="正常" :value="1" />
          <el-option label="停用" :value="0" />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['fk:question_bank:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['fk:question_bank:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['fk:question_bank:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['fk:question_bank:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

          <el-table v-loading="loading" :data="question_bankList || []" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="题库ID" align="center" prop="id" />
        <el-table-column label="题库名称" align="center" prop="name" />
        <el-table-column label="图片地址" align="center" prop="url" width="100">
          <template slot-scope="scope">
            <image-preview v-if="scope.row && scope.row.url" :src="scope.row.url" :width="50" :height="50"/>
            <span v-else class="no-image">无图片</span>
          </template>
        </el-table-column>
        <el-table-column label="所属科目" align="center" prop="subjectName" />
        <el-table-column label="题库类型" align="center" prop="type">
          <template slot-scope="scope">
            <dict-tag v-if="dict.type && dict.type.type" :options="dict.type.type" :value="scope.row.type"/>
            <span v-else>{{ scope.row.type || '未知' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="价格" align="center" prop="price">
          <template slot-scope="scope">
            <span>{{ scope.row.price != null ? Number(scope.row.price).toFixed(2) : '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="题库描述" align="center" prop="description" />
        <el-table-column label="状态" align="center" prop="del" width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row && scope.row.del === 1 ? 'success' : 'danger'">
              {{ scope.row && scope.row.del === 1 ? '正常' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
            v-hasPermi="['fk:question_bank:query']"
          >查看</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['fk:question_bank:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['fk:question_bank:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改题库管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="题库名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入题库名称" />
        </el-form-item>
        <el-form-item label="图片地址" prop="url">
          <el-upload
            class="avatar-uploader"
            action="#"
            :http-request="(options) => customUpload(options)"
            :show-file-list="false"
            :before-upload="beforeUpload"
            accept="image/*"
          >
            <img v-if="form.url" :src="form.url" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="题库类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择题库类型" @change="handleFormTypeChange">
            <el-option
              v-for="dict in (dict.type && dict.type.type) || []"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属科目" prop="subjectId">
          <el-select v-model="form.subjectId" placeholder="请选择所属科目" clearable @change="handleFormSubjectChange">
        <el-form-item label="价格" prop="price">
          <el-input-number v-model="form.price" :min="0" :precision="2" :step="0.1" placeholder="请输入价格" />
        </el-form-item>
        <el-form-item label="所属科目" prop="subjectName">
          <el-select v-model="form.subjectId" placeholder="请选择题库类型">
            <el-option
              v-for="subject in subjectList || []"
              :key="subject.id"
              :label="subject.name"
              :value="subject.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属课程" prop="courseId">
          <el-select
            v-model="form.courseId"
            placeholder="请选择所属课程"
            clearable
            @change="handleFormCourseChange"
            :disabled="form.type !== 'OFFICIAL'"
          >
            <el-option
              v-for="course in formCourseList || []"
              :key="course.id"
              :label="course.name"
              :value="course.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属章节" prop="chapterId">
          <el-select
            v-model="form.chapterId"
            placeholder="请选择所属章节"
            clearable
            @change="handleFormChapterChange"
            :disabled="form.type !== 'OFFICIAL'"
          >
            <el-option
              v-for="chapter in formChapterList || []"
              :key="chapter.id"
              :label="chapter.name"
              :value="chapter.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="题库描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="题目状态" prop="del"  v-if ="open1">
          <el-select  v-model="form.del" placeholder="请选择题目状态"  clearable>
            <el-option
              :key="1"
              label="正常"
              :value="1"
            />
            <el-option
              :key="0"
              label="停用"
              :value="0"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 查看题目列表对话框 -->
    <el-dialog :title="viewTitle" :visible.sync="viewOpen" width="1200px" append-to-body>
      <!-- 题库信息展示区域 -->
      <div class="question-bank-info">
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="info-item">
              <label>题库名称：</label>
              <span class="info-value">{{ currentBankInfo.name }}</span>
            </div>
            <div class="info-item">
              <label>题库类型：</label>
              <span class="info-value">{{ currentBankInfo.type }}</span>
            </div>
            <div class="info-item">
              <label>所属科目：</label>
              <span class="info-value">{{ currentBankInfo.subjectName }}</span>
            </div>
            <!-- 只在OFFICIAL类型时显示课程和章节信息 -->
            <div class="info-item" v-if="currentBankInfo.type === 'OFFICIAL'">
              <label>所属课程：</label>
              <span class="info-value">{{ currentBankInfo.courseName || '暂无课程信息' }}</span>
            </div>
            <div class="info-item" v-if="currentBankInfo.type === 'OFFICIAL'">
              <label>所属章节：</label>
              <span class="info-value">{{ currentBankInfo.chapterName || '暂无章节信息' }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="info-item">
              <label>题库描述：</label>
              <span class="info-value">{{ currentBankInfo.description || '暂无描述' }}</span>
            </div>
            <div class="info-item">
              <label>创建时间：</label>
              <span class="info-value">{{ currentBankInfo.createTime || '未知' }}</span>
            </div>
          </el-col>
        </el-row>
      </div>

      <!-- 题目列表 -->
      <div class="question-list-section">
        <div class="section-title">题目列表</div>
        <el-table v-loading="questionLoading" :data="questionList || []" style="width: 100%">
          <el-table-column label="选择" align="center" width="60">
            <template slot-scope="scope">
              <el-checkbox
                v-model="scope.row.selected"
              />
            </template>
          </el-table-column>
          <el-table-column label="序号" align="center" prop="index" width="80">
            <template slot-scope="scope">
              {{ (questionQueryParams.pageNum - 1) * questionQueryParams.pageSize + scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column label="题目类型" align="center" prop="questionType" width="120">
            <template slot-scope="scope">
              <el-tag :type="getQuestionTypeTag(scope.row.questionType)">
                {{ scope.row.questionType }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="题目内容" align="left" prop="question" min-width="300">
            <template slot-scope="scope">
              <div class="question-content">{{ scope.row.question }}</div>
            </template>
          </el-table-column>
          <el-table-column label="题目图片" align="center" prop="question_url" width="120">
            <template slot-scope="scope">
              <image-preview
                v-if="scope.row.question_url && scope.row.question_url !== '' && scope.row.question_url !== 'null'"
                :src="scope.row.question_url"
                :width="80"
                :height="80"
              />
              <span v-else class="no-image">无图片</span>
            </template>
          </el-table-column>
          <el-table-column label="题目难度" align="center" prop="difficulty" width="150">
            <template slot-scope="scope">
              <el-rate
                v-model="scope.row.difficulty"
                :max="5"
                :show-score="false"
                :show-text="false"
                disabled
                :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
              />
              <span class="difficulty-text">{{ getDifficultyText(scope.row.difficulty) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="250">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-view"
                @click="handleViewAnswer(scope.row)"
              >查看选项</el-button>
<!--              <el-button-->
<!--                size="mini"-->
<!--                type="text"-->
<!--                icon="el-icon-edit"-->
<!--                @click="handleEditQuestion(scope.row)"-->
<!--              >修改</el-button>-->
              <el-button
                size="mini"
                type="text"
                icon="el-icon-view"
                @click="handleDeleteQuestion(scope.row)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 题目列表分页 -->
        <pagination
          v-show="questionTotal > 0"
          :total="questionTotal"
          :page.sync="questionQueryParams.pageNum"
          :limit.sync="questionQueryParams.pageSize"
          @pagination="handleQuestionPagination"
        />

        <!-- 添加和删除按钮 -->
        <div class="question-actions">
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="small"
            @click="handleAddQuestion"
          >添加题目</el-button>
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="small"
            :disabled="!hasSelectedQuestions"
            @click="handleBatchDeleteQuestions"
          >删除选中</el-button>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="viewOpen = false">关 闭</el-button>
      </div>
    </el-dialog>



      <!-- 查看和编辑题目选项弹出层 -->
      <el-dialog :title="viewAnswerTitle" :visible.sync="viewAnswerOpen" width="800px" append-to-body>
        <el-form ref="optionForm" :model="currentQuestionOption" :rules="optionRules" label-width="100px">
          <el-form-item label="题目ID:" prop="questionId">
            <span>{{ currentQuestionOption.questionId || '暂无' }}</span>
          </el-form-item>

          <el-form-item label="题目内容:" prop="question">
            <span>{{ currentQuestionOption.questionTitle || '暂无题目内容' }}</span>
          </el-form-item>

          <el-form-item label="* 选项A" prop="optionA">
            <el-input v-model="currentQuestionOption.optionA" placeholder="请输入选项A" />
          </el-form-item>

          <el-form-item label="* 选项B" prop="optionB">
            <el-input v-model="currentQuestionOption.optionB" placeholder="请输入选项B" />
          </el-form-item>

          <el-form-item label="* 选项C" prop="optionC">
            <el-input v-model="currentQuestionOption.optionC" placeholder="请输入选项C" />
          </el-form-item>

          <el-form-item label="* 选项D" prop="optionD">
            <el-input v-model="currentQuestionOption.optionD" placeholder="请输入选项D" />
          </el-form-item>

          <el-form-item label="* 正确答案" prop="correctOptions">
            <el-select v-model="currentQuestionOption.correctOptions" placeholder="请选择正确答案">
              <el-option label="A" value="A" />
              <el-option label="B" value="B" />
              <el-option label="C" value="C" />
              <el-option label="D" value="D" />
            </el-select>
          </el-form-item>

          <el-form-item label="题目解析" prop="analysis">
            <el-input
              v-model="currentQuestionOption.analysis"
              type="textarea"
              :rows="4"
              placeholder="请输入题目解析"
            />
          </el-form-item>
        </el-form>

        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitOptionForm">确 定</el-button>
          <el-button @click="viewAnswerOpen = false">取 消</el-button>
        </div>
      </el-dialog>

      <!-- 添加题目弹出层 -->
      <el-dialog :title="addQuestionTitle" :visible.sync="addQuestionOpen" width="1200px" append-to-body>
      <!-- 查询条件 -->
<!--      <el-form :model="unlinkedQuestionQueryParams" ref="unlinkedQuestionQueryForm" size="small" :inline="true" label-width="68px">-->
<!--        <el-form-item label="题目标题" prop="title">-->
<!--          <el-input-->
<!--            v-model="unlinkedQuestionQueryParams.title"-->
<!--            placeholder="请输入题目标题"-->
<!--            clearable-->
<!--            @keyup.enter.native="getUnlinkedQuestionList"-->
<!--          />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="题目类型" prop="type">-->
<!--          <el-select v-model="unlinkedQuestionQueryParams.type" placeholder="请选择题目类型" clearable>-->
<!--            <el-option label="选择题" value="选择题" />-->
<!--            <el-option label="填空题" value="填空题" />-->
<!--            <el-option label="计算题" value="计算题" />-->
<!--            <el-option label="实验题" value="实验题" />-->
<!--            <el-option label="简答题" value="简答题" />-->
<!--          </el-select>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="题目难度" prop="difficulty">-->
<!--          <el-select v-model="unlinkedQuestionQueryParams.difficulty" placeholder="请选择题目难度" clearable>-->
<!--            <el-option label="简单" :value="1" />-->
<!--            <el-option label="较简单" :value="2" />-->
<!--            <el-option label="中等" :value="3" />-->
<!--            <el-option label="较难" :value="4" />-->
<!--            <el-option label="困难" :value="5" />-->
<!--          </el-select>-->
<!--        </el-form-item>-->
<!--        <el-form-item>-->
<!--          <el-button type="primary" icon="el-icon-search" size="mini" @click="getUnlinkedQuestionList">搜索</el-button>-->
<!--          <el-button icon="el-icon-refresh" size="mini" @click="resetUnlinkedQuestionQuery">重置</el-button>-->
<!--        </el-form-item>-->
<!--      </el-form>-->

      <!-- 未关联题目列表 -->
      <el-table v-loading="unlinkedQuestionLoading" :data="unlinkedQuestionList || []" style="width: 100%">
        <el-table-column label="选择" align="center" width="60">
          <template slot-scope="scope">
            <el-checkbox
              v-model="scope.row.selected"
            />
          </template>
        </el-table-column>
        <el-table-column label="序号" align="center" prop="index" width="80">
          <template slot-scope="scope">
            {{ (unlinkedQuestionQueryParams.pageNum - 1) * unlinkedQuestionQueryParams.pageSize + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column label="题目类型" align="center" prop="type" width="120">
          <template slot-scope="scope">
            <el-tag :type="getQuestionTypeTag(scope.row.type)">
              {{ scope.row.type }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="题目标题" align="left" prop="title" min-width="300">
          <template slot-scope="scope">
            <div class="question-content">{{ scope.row.title }}</div>
          </template>
        </el-table-column>
        <el-table-column label="题目图片" align="center" prop="question_url" width="120">
          <template slot-scope="scope">
            <image-preview
              v-if="scope.row.question_url && scope.row.question_url !== '' && scope.row.question_url !== 'null'"
              :src="scope.row.question_url"
              :width="80"
              :height="80"
            />
            <span v-else class="no-image">无图片</span>
          </template>
        </el-table-column>
        <el-table-column label="题目难度" align="center" prop="difficulty" width="150">
          <template slot-scope="scope">
            <el-rate
              v-model="scope.row.difficulty"
              :max="5"
              :show-score="false"
              :show-text="false"
              disabled
              :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
            />
            <span class="difficulty-text">{{ getDifficultyText(scope.row.difficulty) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="120">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-plus"
              @click="handleAddSingleQuestion(scope.row)"
            >添加</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination
        v-show="unlinkedQuestionTotal > 0"
        :total="unlinkedQuestionTotal"
        :page.sync="unlinkedQuestionQueryParams.pageNum"
        :limit.sync="unlinkedQuestionQueryParams.pageSize"
        @pagination="handleUnlinkedQuestionPagination"
      />

      <!-- 底部按钮 -->
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleBatchAddQuestions" :disabled="!hasSelectedUnlinkedQuestions">
          批量添加选中题目
        </el-button>
        <el-button @click="addQuestionOpen = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listQuestionBank, getQuestionBank, delQuestionBank, addQuestionBank, updateQuestionBank, getQuestionsByBankId, getUnlinkedQuestions, batchAddQuestions, batchRemoveQuestions,getQuestionBankChapter } from "@/api/fk/question_bank"
import { getQuestionOptionByQuestionId, updateQuestionOption } from "@/api/ssh/questionOption"
import { getAllSubjectNameAndId } from "@/api/ssh/subject"
import { getCourseBySubjectId } from "@/api/ssh/course"
import { getChapterByCourseId } from "@/api/ssh/chapter"
import { uploadFile } from "@/api/oss"

export default {
  name: "Question_bank",
  dicts: ['type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 题库管理表格数据
      question_bankList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      open1:false,

      // 查看题目弹出层标题
      viewTitle: "",
      // 是否显示查看题目弹出层
      viewOpen: false,
      // 当前查看的题库信息
      currentBankInfo: {
        id: null,
        name: '',
        type: '',
        subjectName: '',
        subjectId: null,
        description: '',
        createTime: '',
        courseName: '',
        courseId: null,
        chapterName: '',
        chapterId: null
      },
      // 题目列表数据（静态数据）
      questionList: [
        {
          id: 1,
          question_id: "q001",
          questionType: "选择题",
          question: "在物理学中，牛顿第一定律描述的是什么？A. 力与加速度的关系 B. 作用力与反作用力 C. 物体保持静止或匀速直线运动状态 D. 万有引力定律",
          difficulty: 2,
          question_url: "https://via.placeholder.com/80x80",
          selected: false
        },
        {
          id: 2,
          question_id: "q002",
          questionType: "填空题",
          question: "物体的质量与重力加速度的乘积等于物体的____。",
          difficulty: 1,
          question_url: "https://via.placeholder.com/80x80",
          selected: false
        },
        {
          id: 3,
          question_id: "q003",
          questionType: "计算题",
          question: "一个质量为2kg的物体，在重力作用下从10m高处自由落下，求落地时的速度。（g=9.8m/s²）",
          difficulty: 4,
          question_url: "https://via.placeholder.com/80x80",
          selected: false
        },
        {
          id: 4,
          question_id: "q004",
          questionType: "实验题",
          question: "设计一个实验来验证自由落体运动的规律，要求：1. 列出所需器材 2. 描述实验步骤 3. 分析实验数据",
          difficulty: 5,
          question_url: "https://via.placeholder.com/80x80",
          selected: false
        },
        {
          id: 5,
          question_id: "q005",
          questionType: "选择题",
          question: "下列哪个物理量是标量？A. 力 B. 速度 C. 加速度 D. 质量",
          difficulty: 1,
          question_url: "https://via.placeholder.com/80x80",
          selected: false
        },
        {
          id: 6,
          question_id: "q006",
          questionType: "简答题",
          question: "简述牛顿三大定律的内容，并举例说明其在日常生活中的应用。",
          difficulty: 3,
          question_url: "https://via.placeholder.com/80x80",
          selected: false
        }
      ],
      // 题目列表分页参数
      questionQueryParams: {
        pageNum: 1,
        pageSize: 10,
        bankId: null
      },
      // 题目列表总数
      questionTotal: 0,
      // 题目列表加载状态
      questionLoading: false,

      // 添加题目弹出层
      addQuestionOpen: false,
      addQuestionTitle: "添加题目到题库",

      // 查看和编辑题目选项弹出层
      viewAnswerOpen: false,
      viewAnswerTitle: "管理选项",
      currentQuestionOption: {
        id: null,
        questionId: null,
        optionA: '',
        optionB: '',
        optionC: '',
        optionD: '',
        correctOptions: '',
        analysis: '',
        questionTitle: ''
      },
      optionRules: {
        optionA: [
          { required: true, message: "选项A不能为空", trigger: "blur" }
        ],
        optionB: [
          { required: true, message: "选项B不能为空", trigger: "blur" }
        ],
        optionC: [
          { required: true, message: "选项C不能为空", trigger: "blur" }
        ],
        optionD: [
          { required: true, message: "选项D不能为空", trigger: "blur" }
        ],
        correctOptions: [
          { required: true, message: "正确答案不能为空", trigger: "change" }
        ]
      },



      // 未关联题目列表
      unlinkedQuestionList: [],

      // 未关联题目查询参数
      unlinkedQuestionQueryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
        type: null,
        difficulty: null,
        subjectId: '',
        courseId: '',
        chapterId:''
      },

      // 未关联题目总数
      unlinkedQuestionTotal: 0,

      // 未关联题目加载状态
      unlinkedQuestionLoading: false,

      // 科目列表
      subjectList: [],
      // 课程列表
      courseList: [],
      // 章节列表
      chapterList: [],
      // 表单专用的课程列表
      formCourseList: [],
      // 表单专用的章节列表
      formChapterList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        subjectId: null,
        courseId: null,
        chapterId: null,
        type: null,
        price: null,
        del: null, // null 表示查询所有状态
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "题库名称不能为空", trigger: "blur" }
        ],
        subjectId: [
          { required: true, message: "所属科目不能为空", trigger: "change" }
        ],
        type: [
          { required: true, message: "题库类型不能为空", trigger: "change" }
        ],
        courseId: [
          { required: false, message: "所属课程不能为空", trigger: "change" }
        ],
        chapterId: [
          { required: false, message: "所属章节不能为空", trigger: "change" }
        ]
      }
    }
  },
  computed: {
    /** 是否有选中的题目 */
    hasSelectedQuestions() {
      return this.questionList.some(item => item.selected);
    },

    /** 是否有选中的未关联题目 */
    hasSelectedUnlinkedQuestions() {
      return this.unlinkedQuestionList.some(item => item.selected);
    }
  },
  created() {
    try {
      this.getList()
      this.getSubjectList()
      this.getCourseList()
      this.getChapterList()  // 添加获取章节列表
    } catch (error) {
      console.error('页面初始化失败:', error)
      this.$modal.msgError('页面初始化失败，请刷新重试')
    }
  },
  methods: {
    /** 获取科目列表 */
    getSubjectList() {
      try {
        // 调用科目接口获取数据
        getAllSubjectNameAndId().then(response => {
          if (response.code === 200 && response.data) {
            // 处理可能的分页数据结构
            if (response.data.rows) {
              // 分页数据结构：{ rows: [...], total: 100 }
              this.subjectList = response.data.rows || []
            } else if (Array.isArray(response.data)) {
              // 直接数组结构：[...]
              this.subjectList = response.data
            } else {
              // 其他结构，尝试直接使用
              this.subjectList = response.data || []
            }
            console.log('获取科目列表成功:', this.subjectList)
          } else {
            console.warn('获取科目列表失败:', response.msg)
            // 如果接口失败，使用备用数据
            this.subjectList = [
              { id: 1, name: '物理' },
              { id: 2, name: '数学' },
              { id: 3, name: '化学' },
              { id: 4, name: '生物' },
              { id: 5, name: '英语' },
              { id: 6, name: '科学' }
            ]
          }
        }).catch(error => {
          console.error('调用科目接口失败:', error)
          // 如果接口调用失败，使用备用数据
          this.subjectList = [
            { id: 1, name: '物理' },
            { id: 2, name: '数学' },
            { id: 3, name: '化学' },
            { id: 4, name: '生物' },
            { id: 5, name: '英语' },
            { id: 6, name: '科学' }
          ]
        })
      } catch (error) {
        console.error('获取科目列表失败:', error)
        this.subjectList = []
      }
    },
    /** 获取课程列表 */
    getCourseList(subjectId = null) {
      // 如果没有传入科目ID，使用查询参数中的科目ID
      const targetSubjectId = subjectId || this.queryParams.subjectId

      // 页面加载时传入null，或者用户没有选择科目时，传入null获取所有课程
      console.log('获取课程列表，科目ID:', targetSubjectId)

      getCourseBySubjectId(targetSubjectId).then(response => {
        if (response.code === 200 && response.data) {
          // 处理可能的分页数据结构
          if (response.data.rows) {
            // 分页数据结构：{ rows: [...], total: 100 }
            this.courseList = response.data.rows || []
          } else if (Array.isArray(response.data)) {
            // 直接数组结构：[...]
            this.courseList = response.data
          } else {
            // 其他结构，尝试直接使用
            this.courseList = response.data || []
          }
          console.log('获取课程列表成功:', this.courseList)
        } else {
          console.warn('获取课程列表失败:', response.msg)
          this.courseList = []
        }
      }).catch(error => {
        console.error('调用课程接口失败:', error)
        this.courseList = []
      })
    },


    /** 获取章节列表 */
    getChapterList(courseId = null) {
      // 页面加载时传入null，或者用户没有选择课程时，传入null获取所有章节
      console.log('获取章节列表，课程ID:', courseId)

      getChapterByCourseId(courseId).then(response => {
        if (response.code === 200 && response.data) {
          // 处理可能的分页数据结构
          if (response.data.rows) {
            // 分页数据结构：{ rows: [...], total: 100 }
            this.chapterList = response.data.rows || []
          } else if (Array.isArray(response.data)) {
            // 直接数组结构：[...]
            this.chapterList = response.data
          } else {
            // 其他结构，尝试直接使用
            this.chapterList = response.data || []
          }
          console.log('获取章节列表成功:', this.chapterList);
        } else {
          console.warn('获取章节列表失败:', response.msg);
          this.chapterList = [];
        }
      }).catch(error => {
        console.error('调用章节接口失败:', error);
        this.chapterList = [];
      });
    },


    /** 查询题库管理列表 */
    getList() {
      try {
        this.loading = true
        listQuestionBank(this.queryParams).then(response => {
          console.log('API response:', response)
          this.question_bankList = response.rows || []
          this.total = response.total || 0
          this.loading = false
        }).catch(error => {
        console.error('API error:', error)
        this.loading = false
        // 如果接口失败，使用静态数据作为备用
        this.question_bankList = [
          {
            id: 1,
            name: "物理选择题集合",
            url: "https://via.placeholder.com/50x50",
            subjectId: 1,
            type: "OFFICIAL",
            description: "物理力学基础选择题"
          },
          {
            id: 2,
            name: "物理实验题定制",
            url: "https://via.placeholder.com/50x50",
            subjectId: 1,
            type: "CUSTOM",
            description: "用户上传的力学实验题"
          },
          {
            id: 3,
            name: "数学公式推导题",
            url: "https://via.placeholder.com/50x50",
            subjectId: 2,
            type: "OFFICIAL",
            description: "代数公式推导专项"
          },
          {
            id: 4,
            name: "数学压轴题精选",
            url: "https://via.placeholder.com/50x50",
            subjectId: 2,
            type: "EXCLUSIVE",
            description: "付费专属数学压轴题"
          },
          {
            id: 5,
            name: "化学方程式练习",
            url: "https://via.placeholder.com/50x50",
            subjectId: 3,
            type: "OFFICIAL",
            description: "基础方程式配平题"
          },
          {
            id: 6,
            name: "化学实验设计题",
            url: "https://via.placeholder.com/50x50",
            subjectId: 3,
            type: "CUSTOM",
            description: "教师定制实验设计题"
          }
        ]
        this.total = this.question_bankList.length
        this.$modal.msgWarning("接口调用失败，显示静态数据")
      })
      } catch (error) {
        console.error('getList方法执行失败:', error)
        this.loading = false
        this.$modal.msgError('获取题库列表失败，请刷新重试')
      }
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        url: null,
        subjectId: null,
        courseId: null,
        chapterId: null,
        type: null,
        price: null,
        description: null,
        createTime: null,
        del: 1  // 默认状态为正常
      }
      // 清空表单专用的列表
      this.formCourseList = []
      this.formChapterList = []
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.open1 = false
      this.title = "添加题库管理"

      // 确保表单打开时就加载所有课程和章节数据
      this.getFormCourseList(null)  // 传入null获取所有课程
      this.getFormChapterList(null) // 传入null获取所有章节
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getQuestionBank(id).then(response => {
        this.form = response.data
        this.open = true
        this.open1 = true
        this.title = "修改题库管理"

        // 先加载所有课程和章节数据
        this.getFormCourseList(null)
        this.getFormChapterList(null)

        // 如果有科目ID，重新加载对应的课程列表
        if (this.form.subjectId) {
          this.getFormCourseList(this.form.subjectId)
        }

        // 如果有课程ID，重新加载对应的章节列表
        if (this.form.courseId) {
          this.getFormChapterList(this.form.courseId)
        }
      })
    },
    /** 查看按钮操作 */
    handleView(row) {
      // 判断题目类型是否为"OFFICIAL"
      if (row.type === 'OFFICIAL') {
        // 调用章节练习专用接口获取详细数据
        getQuestionBankChapter(row.id).then(response => {
          if (response.code === 200 && response.data) {
            this.viewTitle = `查看题库：${response.data.name}`;

            // 设置完整的题库信息，包含课程和章节信息
            this.currentBankInfo = {
              id: response.data.id,
              name: response.data.name,
              type: response.data.type,
              subjectName: response.data.subjectName,
              subjectId: response.data.subjectId,        // 添加科目ID
              description: response.data.description,
              createTime: response.data.createTime,
              courseName: response.data.courseName,
              courseId: response.data.courseId,          // 添加课程ID
              chapterName: response.data.chapterName,
              chapterId: response.data.chapterId         // 添加章节ID
            };
            this.viewOpen = true;
            console.log('=== 添加题目调试信息 ===');
            console.log('当前题库信息:', this.currentBankInfo);
            console.log('科目名称:', this.currentBankInfo.subjectName);
            console.log('科目ID:', this.currentBankInfo.subjectId);
            console.log('课程ID:', this.currentBankInfo.courseId);
            console.log('章节ID:', this.currentBankInfo.chapterId);
            // 重置分页参数
            this.questionQueryParams.pageNum = 1;
            this.questionQueryParams.pageSize = 10;
            this.questionQueryParams.bankId = row.id;

            // 获取题目列表
            this.getQuestionList();
          } else {
            this.$modal.msgError('获取章节练习数据失败：' + (response.msg || '未知错误'));
          }
        }).catch(error => {
          console.error('获取章节练习数据失败:', error);
          this.$modal.msgError('获取章节练习数据失败，请稍后重试');
        });
      } else {
        // 原有的查看逻辑
        this.viewTitle = `查看题库：${row.name}`;

        // 设置基本题库信息，不包含课程和章节
        this.currentBankInfo = {
          id: row.id,
          name: row.name,
          type: row.type,
          subjectName: row.subjectName,
          subjectId: row.subjectId,        // 添加科目ID
          description: row.description,
          createTime: row.createTime,
          courseName: '',                  // 非OFFICIAL类型，清空课程信息
          courseId: null,                  // 非OFFICIAL类型，清空课程ID
          chapterName: '',                 // 非OFFICIAL类型，清空章节信息
          chapterId: null                  // 非OFFICIAL类型，清空章节ID
        };

        this.viewOpen = true;

        // 重置分页参数
        this.questionQueryParams.pageNum = 1;
        this.questionQueryParams.pageSize = 10;
        this.questionQueryParams.bankId = row.id;

        // 获取题目列表
        this.getQuestionList();
      }
    },
    /** 查看答案操作 */
    handleViewAnswer(row) {
      // 设置弹出框标题
      this.viewAnswerTitle = `管理选项：${row.question.substring(0, 20)}...`

      // 获取题目ID
      const questionId = row.question_id || row.id

      if (!questionId) {
        this.$modal.msgError('题目ID信息缺失，无法获取选项信息')
        return
      }

      // 调用API获取题目选项信息
      getQuestionOptionByQuestionId(questionId).then(response => {
        if (response.code === 200 && response.data) {
          // 将题目内容也添加到选项中，方便显示
          this.currentQuestionOption = {
            id: response.data.id || null,
            questionId: response.data.questionId || questionId,
            optionA: response.data.optionA || '',
            optionB: response.data.optionB || '',
            optionC: response.data.optionC || '',
            optionD: response.data.optionD || '',
            correctOptions: response.data.correctOptions || '',
            analysis: response.data.analysis || '',
            // 设置题目标题用于显示，但不发送到后端
            questionTitle: row.question || ''
          }
          this.viewAnswerOpen = true
        } else {
          this.$modal.msgError('获取题目选项失败：' + (response.msg || '未知错误'))
        }
      }).catch(error => {
        console.error('获取题目选项失败:', error)
        let errorMsg = '获取题目选项失败'
        if (error.response && error.response.data) {
          errorMsg += '：' + error.response.data.msg
        } else if (error.message) {
          errorMsg += '：' + error.message
        }
        this.$modal.msgError(errorMsg)
      })
    },
    /** 修改题目操作 */
    handleEditQuestion(row) {
      this.$modal.msgInfo(`修改题目"${row.question.substring(0, 20)}..."`)
    },
    /** 删除题目操作 */
    handleDeleteQuestion(row) {
      console.log('删除题目，行数据:', row); // 调试日志

      // 验证必要的数据字段
      if (!this.currentBankInfo || !this.currentBankInfo.id) {
        this.$modal.msgError('题库信息不完整，无法删除');
        return;
      }

      if (!row.question_id && !row.id) {
        this.$modal.msgError('题目ID信息缺失，无法删除');
        return;
      }

      this.$modal.confirm(`是否确认删除题目"${row.question.substring(0, 20)}..."？`).then(() => {
        // 调用后端接口删除题目与题库的关联关系
        const mapping = {
          bankId: this.currentBankInfo.id,
          questionId: row.question_id || row.id
        };

        console.log('发送删除请求，映射数据:', mapping); // 调试日志

        batchRemoveQuestions([mapping]).then(response => {
          console.log('删除接口响应:', response); // 调试日志

          if (response.code === 200) {
            // 删除成功后重新获取题目列表，确保数据同步
            this.getQuestionList();
            this.$modal.msgSuccess("删除成功");
          } else {
            this.$modal.msgError('删除失败：' + (response.msg || '未知错误'));
          }
        }).catch(error => {
          console.error('删除题目失败:', error);
          let errorMsg = '删除题目失败';
          if (error.response && error.response.data) {
            errorMsg += '：' + error.response.data.msg;
          } else if (error.message) {
            errorMsg += '：' + error.message;
          }
          this.$modal.msgError(errorMsg);
        });
      }).catch(() => {})
    },
    /** 获取题目类型标签样式 */
    getQuestionTypeTag(type) {
      const typeMap = {
        '选择题': 'primary',
        '填空题': 'success',
        '计算题': 'warning',
        '实验题': 'danger',
        '简答题': 'info'
      }
      return typeMap[type] || 'info'
    },
    /** 获取难度文字描述 */
    getDifficultyText(difficulty) {
      const difficultyMap = {
        1: '简单',
        2: '较简单',
        3: '中等',
        4: '较难',
        5: '困难'
      }
      return difficultyMap[difficulty] || '未知'
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateQuestionBank(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addQuestionBank(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除题库管理编号为"' + ids + '"的数据项？').then(function() {
        return delQuestionBank(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('fk/question_bank/export', {
        ...this.queryParams
      }, `question_b_${new Date().getTime()}.xlsx`)
    },
    /** 批量删除选中题目 */
    handleBatchDeleteQuestions() {
      const selectedQuestions = this.questionList.filter(item => item.selected);
      if (selectedQuestions.length === 0) {
        this.$modal.msgWarning('请选择要删除的题目');
        return;
      }

      // 验证必要的数据字段
      if (!this.currentBankInfo || !this.currentBankInfo.id) {
        this.$modal.msgError('题库信息不完整，无法删除');
        return;
      }

      console.log('批量删除，选中的题目:', selectedQuestions); // 调试日志

      this.$modal.confirm(`确定要删除选中的 ${selectedQuestions.length} 道题目吗？`).then(() => {
        // 调用后端接口批量删除题目与题库的关联关系
        const mappings = selectedQuestions.map(item => ({
          bankId: this.currentBankInfo.id,
          questionId: item.question_id || item.id
        }));

        console.log('发送批量删除请求，映射数据:', mappings); // 调试日志

        batchRemoveQuestions(mappings).then(response => {
          console.log('批量删除接口响应:', response); // 调试日志

          if (response.code === 200) {
            // 删除成功后重新获取题目列表，确保数据同步
            this.getQuestionList();
            this.$modal.msgSuccess('批量删除成功');
          } else {
            this.$modal.msgError('批量删除失败：' + (response.msg || '未知错误'));
          }
        }).catch(error => {
          console.error('批量删除题目失败:', error);
          let errorMsg = '批量删除题目失败';
          if (error.response && error.response.data) {
            errorMsg += '：' + error.response.data.msg;
          } else if (error.message) {
            errorMsg += '：' + error.message;
          }
          this.$modal.msgError(errorMsg);
        });
      }).catch(() => {});
    },
    /** 添加新题目 */
    handleAddQuestion() {
      this.addQuestionOpen = true;
      this.addQuestionTitle = `添加题目到题库：${this.currentBankInfo.name}`;

      // 根据题库类型设置不同的查询参数
      if (this.currentBankInfo.type === 'OFFICIAL') {
        // OFFICIAL类型：传入科目ID、课程ID、章节ID
        this.unlinkedQuestionQueryParams = {
          pageNum: 1,
          pageSize: 10,
          title: null,
          type: null,
          difficulty: null,
          subjectId: this.currentBankInfo.subjectId,        // 题库所属科目ID
          courseId: this.currentBankInfo.courseId,          // 题库所属课程ID
          chapterId: this.currentBankInfo.chapterId,        // 题库所属章节ID
          bankType: this.currentBankInfo.type               // 题库类型
        };
      } else {
        // 非OFFICIAL类型：只传入科目ID
        this.unlinkedQuestionQueryParams = {
          pageNum: 1,
          pageSize: 10,
          title: null,
          type: null,
          difficulty: null,
          subjectId: this.currentBankInfo.subjectId,        // 题库所属科目ID
          courseId: null,                                   // 非OFFICIAL类型，不传课程ID
          chapterId: null,                                  // 非OFFICIAL类型，不传章节ID
          bankType: this.currentBankInfo.type               // 题库类型
        };
      }

      // 添加调试日志
      console.log('=== 添加题目调试信息 ===');
      console.log('当前题库信息:', this.currentBankInfo);
      console.log('题库类型:', this.currentBankInfo.type);
      console.log('筛选参数:', this.unlinkedQuestionQueryParams);
      console.log('科目名称:', this.currentBankInfo.subjectName);
      console.log('科目ID:', this.currentBankInfo.subjectId);
      console.log('课程ID:', this.currentBankInfo.courseId);
      console.log('章节ID:', this.currentBankInfo.chapterId);

      // 获取未关联的题目列表
      this.getUnlinkedQuestionList();
    },
    /** 获取题目列表 */
    getQuestionList() {
      // 检查是否有有效的题库ID
      if (!this.currentBankInfo || !this.currentBankInfo.id) {
        console.warn('题库信息不完整，无法获取题目列表');
        this.questionLoading = false;
        return;
      }

      this.questionLoading = true;
      getQuestionsByBankId(this.currentBankInfo.id, this.questionQueryParams).then(response => {
        if (response.code === 200 && response.data) {
          // 将后端数据转换为前端需要的格式
          this.questionList = (response.data.records || response.data || []).map(item => ({
            id: item.question_id || item.id || Math.random().toString(36).substr(2, 9),
            questionType: item.type || '未知类型',
            question: item.title || '无标题',
            difficulty: item.difficulty || 1,
            question_url: item.question_url || item.url || '',
            question_id: item.question_id || item.id,
            selected: false
          }));

          // 设置总数，支持不同的后端返回格式
          if (response.data.total !== undefined) {
            this.questionTotal = response.data.total;
          } else if (response.data.length !== undefined) {
            this.questionTotal = response.data.length;
          } else {
            this.questionTotal = this.questionList.length;
          }

          this.questionLoading = false;

          // 调试输出
          console.log('后端原始数据:', response.data);
          console.log('转换后的题目列表:', this.questionList);
          console.log('题目总数:', this.questionTotal);
        } else {
          this.$modal.msgError("获取题目列表失败：" + (response.msg || '未知错误'));
          this.questionLoading = false;
        }
      }).catch(error => {
        console.error('获取题目列表失败:', error);
        this.$modal.msgError("获取题目列表失败，请稍后重试");
        this.questionLoading = false;

        // 如果接口失败，使用静态数据作为备用
        this.questionList = [
          {
            id: 1,
            question_id: "q001",
            questionType: "选择题",
            question: "在物理学中，牛顿第一定律描述的是什么？A. 力与加速度的关系 B. 作用力与反作用力 C. 物体保持静止或匀速直线运动状态 D. 万有引力定律",
            difficulty: 2,
            question_url: "https://via.placeholder.com/80x80",
            selected: false
          },
          {
            id: 2,
            question_id: "q002",
            questionType: "填空题",
            question: "物体的质量与重力加速度的乘积等于物体的____。",
            difficulty: 1,
            question_url: "https://via.placeholder.com/80x80",
            selected: false
          },
          {
            id: 3,
            question_id: "q003",
            questionType: "计算题",
            question: "一个质量为2kg的物体，在重力作用下从10m高处自由落下，求落地时的速度。（g=9.8m/s²）",
            difficulty: 4,
            question_url: "https://via.placeholder.com/80x80",
            selected: false
          },
          {
            id: 4,
            question_id: "q004",
            questionType: "实验题",
            question: "设计一个实验来验证自由落体运动的规律，要求：1. 列出所需器材 2. 描述实验步骤 3. 分析实验数据",
            difficulty: 5,
            question_url: "https://via.placeholder.com/80x80",
            selected: false
          },
          {
            id: 5,
            question_id: "q005",
            questionType: "选择题",
            question: "下列哪个物理量是标量？A. 力 B. 速度 C. 加速度 D. 质量",
            difficulty: 1,
            question_url: "https://via.placeholder.com/80x80",
            selected: false
          },
          {
            id: 6,
            question_id: "q006",
            questionType: "简答题",
            question: "简述牛顿三大定律的内容，并举例说明其在日常生活中的应用。",
            difficulty: 3,
            question_url: "https://via.placeholder.com/80x80",
            selected: false
          }
        ];
        this.questionTotal = this.questionList.length;
      });
    },
          /** 分页变化处理 */
      handleQuestionPagination(pagination) {
        this.questionQueryParams.pageNum = pagination.page;
        this.questionQueryParams.pageSize = pagination.limit;
        this.getQuestionList();
      },

      /** 获取未关联题目列表 */
      getUnlinkedQuestionList() {
        this.unlinkedQuestionLoading = true;
        getUnlinkedQuestions(this.currentBankInfo.id, this.unlinkedQuestionQueryParams).then(response => {
          if (response.code === 200 && response.data) {
            this.unlinkedQuestionList = response.data.map(item => ({
              id: item.id,
              title: item.title,
              type: item.type,
              difficulty: item.difficulty,
              question_url: item.question_url || '',
              selected: false
            }));

            this.unlinkedQuestionTotal = this.unlinkedQuestionList.length;
            this.unlinkedQuestionLoading = false;
          } else {
            this.$modal.msgError("获取未关联题目列表失败：" + (response.msg || '未知错误'));
            this.unlinkedQuestionLoading = false;
          }
        }).catch(error => {
          console.error('获取未关联题目列表失败:', error);
          this.$modal.msgError("获取未关联题目列表失败，请稍后重试");
          this.unlinkedQuestionLoading = false;
        });
      },

      /** 批量添加题目到题库 */
      handleBatchAddQuestions() {
        const selectedQuestions = this.unlinkedQuestionList.filter(item => item.selected);
        if (selectedQuestions.length === 0) {
          this.$modal.msgWarning('请选择要添加的题目');
          return;
        }

        // 检查是否已经有关联关系
        const existingQuestions = this.questionList.filter(q =>
          selectedQuestions.some(sq => sq.id === q.question_id || sq.id === q.id)
        );

        if (existingQuestions.length > 0) {
          const questionNames = existingQuestions.map(q => q.question.substring(0, 20) + '...').join('、');
          this.$modal.msgWarning(`以下题目已经存在于题库中：${questionNames}`);
          return;
        }

        const mappings = selectedQuestions.map(item => ({
          bankId: this.currentBankInfo.id,
          questionId: item.id
        }));

        batchAddQuestions(mappings).then(response => {
          if (response.code === 200) {
            this.$modal.msgSuccess('添加题目成功');
            this.addQuestionOpen = false;

            // 重新获取题库中的题目列表
            this.getQuestionList();

            // 重新获取未关联题目列表，移除已添加的题目
            this.getUnlinkedQuestionList();
          } else {
            this.$modal.msgError('添加题目失败：' + (response.msg || '未知错误'));
          }
        }).catch(error => {
          console.error('添加题目失败:', error);
          let errorMsg = '添加题目失败';
          if (error.response && error.response.data) {
            errorMsg += '：' + error.response.data.msg;
          } else if (error.message) {
            errorMsg += '：' + error.message;
          }
          this.$modal.msgError(errorMsg);
        });
      },



      /** 未关联题目分页变化处理 */
      handleUnlinkedQuestionPagination(pagination) {
        this.unlinkedQuestionQueryParams.pageNum = pagination.page;
        this.unlinkedQuestionQueryParams.pageSize = pagination.limit;
        this.getUnlinkedQuestionList();
      },

      /** 添加单个题目到题库 */
      handleAddSingleQuestion(row) {
        // 检查是否已经有关联关系
        const existingQuestion = this.questionList.find(q =>
          q.question_id === row.id || q.id === row.id
        );

        if (existingQuestion) {
          this.$modal.msgWarning(`题目"${row.title.substring(0, 20)}..."已经存在于题库中`);
          return;
        }

        const mapping = {
          bankId: this.currentBankInfo.id,
          questionId: row.id
        };

        batchAddQuestions([mapping]).then(response => {
          if (response.code === 200) {
            this.$modal.msgSuccess('添加题目成功');

            // 重新获取题库中的题目列表
            this.getQuestionList();

            // 重新获取未关联题目列表，移除已添加的题目
            this.getUnlinkedQuestionList();
          } else {
            this.$modal.msgError('添加题目失败：' + (response.msg || '未知错误'));
          }
        }).catch(error => {
          console.error('添加题目失败:', error);
          let errorMsg = '添加题目失败';
          if (error.response && error.response.data) {
            errorMsg += '：' + error.response.data.msg;
          } else if (error.message) {
            errorMsg += '：' + error.message;
          }
          this.$modal.msgError(errorMsg);
        });
      },

      /** 重置未关联题目查询条件 */
      resetUnlinkedQuestionQuery() {
        this.resetForm("unlinkedQuestionQueryForm");
        this.unlinkedQuestionQueryParams = {
          pageNum: 1,
          pageSize: 10,
          title: null,
          type: null,
          difficulty: null,
          subjectId: this.currentBankInfo.subjectId || null,        // 保持题库的科目ID
          courseId: this.currentBankInfo.courseId || null,          // 保持题库的课程ID
          chapterId: this.currentBankInfo.chapterId || null         // 保持题库的章节ID
        };
        this.getUnlinkedQuestionList();
      },

      /** 提交选项表单 */
      submitOptionForm() {
        this.$refs["optionForm"].validate(valid => {
          if (valid) {
            // 构造发送到后端的数据，排除前端显示用的字段
            const submitData = {
              id: this.currentQuestionOption.id,
              questionId: this.currentQuestionOption.questionId,
              optionA: this.currentQuestionOption.optionA,
              optionB: this.currentQuestionOption.optionB,
              optionC: this.currentQuestionOption.optionC,
              optionD: this.currentQuestionOption.optionD,
              correctOptions: this.currentQuestionOption.correctOptions,
              analysis: this.currentQuestionOption.analysis
            }

            // 调用更新接口
            updateQuestionOption(submitData).then(response => {
              if (response.code === 200) {
                this.$modal.msgSuccess("更新成功")
                this.viewAnswerOpen = false
                // 可以在这里刷新题目列表
                this.getQuestionList()
              } else {
                this.$modal.msgError('更新失败：' + (response.msg || '未知错误'))
              }
            }).catch(error => {
              console.error('更新题目选项失败:', error)
              let errorMsg = '更新题目选项失败'
              if (error.response && error.response.data) {
                errorMsg += '：' + error.response.data.msg
              } else if (error.message) {
                errorMsg += '：' + error.message
              }
              this.$modal.msgError(errorMsg)
            })
          }
        })
      },
      /** 课程变化时更新章节列表 */
      handleCourseChange(courseId) {
        console.log('课程选择变化，课程ID:', courseId);

        // 清空章节选择
        this.queryParams.chapterId = null;

        // 根据选择的课程，查询对应的科目信息并更新
        if (courseId) {
          this.getSubjectByCourseId(courseId);
        }

        // 更新章节列表
        this.getChapterList(courseId);
      },

      /** 根据课程ID获取科目信息 */
      getSubjectByCourseId(courseId) {
        console.log('根据课程ID获取科目信息:', courseId);

        // 从课程列表中查找对应的课程信息
        const selectedCourse = this.courseList.find(course => course.id === courseId);
        if (selectedCourse) {
          console.log('找到选中的课程:', selectedCourse);

          // 如果课程对象中有科目信息，直接使用
          if (selectedCourse.subjectId) {
            this.queryParams.subjectId = selectedCourse.subjectId;
            console.log('根据课程自动设置科目ID:', selectedCourse.subjectId);
          } else if (selectedCourse.subject && selectedCourse.subject.id) {
            // 如果课程对象中有科目对象
            this.queryParams.subjectId = selectedCourse.subject.id;
            console.log('根据课程自动设置科目ID:', selectedCourse.subject.id);
          } else {
            // 如果课程对象中没有科目信息，需要调用API查询
            this.querySubjectByCourseId(courseId);
          }
        } else {
          console.warn('未找到对应的课程信息，课程ID:', courseId);
        }
      },

      /** 调用API查询课程对应的科目 */
      querySubjectByCourseId(courseId) {
        console.log('调用API查询课程对应的科目:', courseId);

        // 这里可以调用一个专门的API来获取课程对应的科目信息
        // 或者通过课程详情接口获取
        import('@/api/ssh/course').then(module => {
          module.getCourse(courseId).then(response => {
            if (response.code === 200 && response.data) {
              const courseData = response.data;
              console.log('课程详情数据:', courseData);

              if (courseData.subjectId) {
                this.queryParams.subjectId = courseData.subjectId;
                console.log('通过API查询到课程对应的科目ID:', courseData.subjectId);
              } else if (courseData.subject && courseData.subject.id) {
                this.queryParams.subjectId = courseData.subject.id;
                console.log('通过API查询到课程对应的科目ID:', courseData.subject.id);
              }
            }
          }).catch(error => {
            console.error('查询课程详情失败:', error);
          });
        });
      },

      /** 科目变化时更新课程列表 */
      handleSubjectChange(subjectId) {
        console.log('科目选择变化，科目ID:', subjectId);

        // 清空课程和章节选择
        this.queryParams.courseId = null;
        this.queryParams.chapterId = null;

        // 更新课程列表
        this.getCourseList(subjectId);

        // 清空章节列表
        this.chapterList = [];
      },

      /** 章节变化时更新课程和科目 */
      handleChapterChange(chapterId) {
        console.log('章节选择变化，章节ID:', chapterId);

        if (chapterId) {
          // 根据选择的章节，自动设置对应的课程ID和科目ID
          this.getCourseAndSubjectByChapterId(chapterId);
        }
      },

      /** 根据章节ID获取课程和科目信息 */
      getCourseAndSubjectByChapterId(chapterId) {
        console.log('根据章节ID获取课程和科目信息:', chapterId);

        // 从章节列表中查找对应的章节信息
        const selectedChapter = this.chapterList.find(chapter => chapter.id === chapterId);
        if (selectedChapter) {
          console.log('找到选中的章节:', selectedChapter);

          // 如果章节对象中有课程信息，直接使用
          if (selectedChapter.courseId) {
            this.queryParams.courseId = selectedChapter.courseId;
            console.log('根据章节自动设置课程ID:', selectedChapter.courseId);

            // 继续查询课程对应的科目
            this.getSubjectByCourseId(selectedChapter.courseId);
          } else if (selectedChapter.course && selectedChapter.course.id) {
            // 如果章节对象中有课程对象
            this.queryParams.courseId = selectedChapter.course.id;
            console.log('根据章节自动设置课程ID:', selectedChapter.course.id);

            // 继续查询课程对应的科目
            this.getSubjectByCourseId(selectedChapter.course.id);
          } else {
            // 如果章节对象中没有课程信息，需要调用API查询
            this.queryCourseByChapterId(chapterId);
          }
        } else {
          console.warn('未找到对应的章节信息，章节ID:', chapterId);
        }
      },

      /** 调用API查询章节对应的课程 */
      queryCourseByChapterId(chapterId) {
        console.log('调用API查询章节对应的课程:', chapterId);

        // 调用章节详情接口获取课程信息
        import('@/api/ssh/chapter').then(module => {
          module.getChapter(chapterId).then(response => {
            if (response.code === 200 && response.data) {
              const chapterData = response.data;
              console.log('章节详情数据:', chapterData);

              if (chapterData.courseId) {
                this.queryParams.courseId = chapterData.courseId;
                console.log('通过API查询到章节对应的课程ID:', chapterData.courseId);

                // 继续查询课程对应的科目
                this.getSubjectByCourseId(chapterData.courseId);
              } else if (chapterData.course && chapterData.course.id) {
                this.queryParams.courseId = chapterData.course.id;
                console.log('通过API查询到章节对应的课程ID:', chapterData.course.id);

                // 继续查询课程对应的科目
                this.getSubjectByCourseId(chapterData.course.id);
              }
            }
          }).catch(error => {
            console.error('查询章节详情失败:', error);
          });
        });
      },
      // 图片上传相关方法
      beforeUpload(file) {
        // 文件类型验证
        const isImage = file.type.startsWith('image/');
        if (!isImage) {
          this.$message.error('只能上传图片文件!');
          return false;
        }

        // 文件大小验证 (5MB)
        const isLt5M = file.size / 1024 / 1024 < 5;
        if (!isLt5M) {
          this.$message.error('图片大小不能超过 5MB!');
          return false;
        }

        return true;
      },
      // 自定义上传方法，使用oss.js中的uploadFile
      async customUpload(options) {
        try {
          const { file } = options;

          // 显示上传进度
          this.$modal.loading("正在上传图片，请稍候...");

          // 创建FormData
          const formData = new FormData();
          formData.append("file", file);

          // 调用oss.js中的uploadFile方法
          const response = await uploadFile(formData);

          // 调试信息：打印完整的响应数据
          console.log('OSS上传响应:', response);

          if (response.code === 200) {
            this.$message.success("图片上传成功");
            // 注意：后端返回的url在response根级别，不是在data中
            const imageUrl = response.url || response.data?.url;
            if (imageUrl) {
              this.form.url = imageUrl;
            } else {
              console.error('响应中没有找到图片URL:', response);
              this.$message.error("上传成功但未获取到图片URL");
            }
          } else {
            this.$message.error(response.msg || "上传失败");
          }
        } catch (error) {
          console.error('上传失败:', error);
          this.$message.error("上传失败：" + (error.message || '未知错误'));
        } finally {
          this.$modal.closeLoading();
        }

        // 通知el-upload组件上传完成
        options.onSuccess();
      },

      /** 表单科目变化时更新课程列表 */
      handleFormSubjectChange(subjectId) {
        console.log('表单科目选择变化，科目ID:', subjectId);

        // 清空课程和章节选择
        this.form.courseId = null;
        this.form.chapterId = null;

        // 更新表单课程列表
        this.getFormCourseList(subjectId);

        // 清空表单章节列表
        this.formChapterList = [];
      },

      /** 表单课程变化时更新章节列表 */
      handleFormCourseChange(courseId) {
        console.log('表单课程选择变化，课程ID:', courseId);

        // 清空章节选择
        this.form.chapterId = null;

        // 根据选择的课程，查询对应的科目信息并更新
        if (courseId) {
          this.getFormSubjectByCourseId(courseId);
        }

        // 更新章节列表
        this.getFormChapterList(courseId);
      },

      /** 表单章节变化时更新课程和科目 */
      handleFormChapterChange(chapterId) {
        console.log('表单章节选择变化，章节ID:', chapterId);

        if (chapterId) {
          // 根据选择的章节，自动设置对应的课程ID和科目ID
          this.getFormCourseAndSubjectByChapterId(chapterId);
        } else {
          // 当取消选择章节时，重新加载所有章节列表
          console.log('取消选择章节，重新加载所有章节列表');
          this.getFormChapterList(null);
        }
      },

      /** 获取表单课程列表 */
      getFormCourseList(subjectId = null) {
        console.log('获取表单课程列表，科目ID:', subjectId);

        getCourseBySubjectId(subjectId).then(response => {
          if (response.code === 200 && response.data) {
            if (response.data.rows) {
              this.formCourseList = response.data.rows || [];
            } else if (Array.isArray(response.data)) {
              this.formCourseList = response.data;
            } else {
              this.formCourseList = response.data || [];
            }
            console.log('获取表单课程列表成功:', this.formCourseList);
          } else {
            console.warn('获取表单课程列表失败:', response.msg);
            this.formCourseList = [];
          }
        }).catch(error => {
          console.error('调用表单课程接口失败:', error);
          this.formCourseList = [];
        });
      },

      /** 获取表单章节列表 */
      getFormChapterList(courseId = null) {
        console.log('获取表单章节列表，课程ID:', courseId);

        getChapterByCourseId(courseId).then(response => {
          if (response.code === 200 && response.data) {
            if (response.data.rows) {
              this.formChapterList = response.data.rows || [];
            } else if (Array.isArray(response.data)) {
              this.formChapterList = response.data;
            } else {
              this.formChapterList = response.data || [];
            }
            console.log('获取表单章节列表成功:', this.formChapterList);
          } else {
            console.warn('获取表单章节列表失败:', response.msg);
            this.formChapterList = [];
          }
        }).catch(error => {
          console.error('调用表单章节接口失败:', error);
          this.formChapterList = [];
        });
      },

      /** 根据表单章节ID获取课程和科目信息 */
      getFormCourseAndSubjectByChapterId(chapterId) {
        console.log('根据表单章节ID获取课程和科目信息:', chapterId);

        const selectedChapter = this.formChapterList.find(chapter => chapter.id === chapterId);
        if (selectedChapter) {
          console.log('找到选中的章节:', selectedChapter);

          if (selectedChapter.courseId) {
            this.form.courseId = selectedChapter.courseId;
            console.log('根据章节自动设置课程ID:', selectedChapter.courseId);

            // 继续查询课程对应的科目
            this.getFormSubjectByCourseId(selectedChapter.courseId);
          } else if (selectedChapter.course && selectedChapter.course.id) {
            this.form.courseId = selectedChapter.course.id;
            console.log('根据章节自动设置课程ID:', selectedChapter.course.id);

            // 继续查询课程对应的科目
            this.getFormSubjectByCourseId(selectedChapter.course.id);
          } else {
            this.queryFormCourseByChapterId(chapterId);
          }
        } else {
          console.warn('未找到对应的章节信息，章节ID:', chapterId);
        }
      },

      /** 根据表单课程ID获取科目信息 */
      getFormSubjectByCourseId(courseId) {
        console.log('根据表单课程ID获取科目信息:', courseId);

        const selectedCourse = this.formCourseList.find(course => course.id === courseId);
        if (selectedCourse) {
          console.log('找到选中的课程:', selectedCourse);

          if (selectedCourse.subjectId) {
            this.form.subjectId = selectedCourse.subjectId;
            console.log('根据课程自动设置科目ID:', selectedCourse.subjectId);
          } else if (selectedCourse.subject && selectedCourse.subject.id) {
            this.form.subjectId = selectedCourse.subject.id;
            console.log('根据课程自动设置科目ID:', selectedCourse.subject.id);
          } else {
            this.queryFormSubjectByCourseId(courseId);
          }
        } else {
          console.warn('未找到对应的课程信息，课程ID:', courseId);
        }
      },

      /** 调用API查询表单课程对应的科目 */
      queryFormSubjectByCourseId(courseId) {
        console.log('调用API查询表单课程对应的科目:', courseId);

        import('@/api/ssh/course').then(module => {
          module.getCourse(courseId).then(response => {
            if (response.code === 200 && response.data) {
              const courseData = response.data;
              console.log('课程详情数据:', courseData);

              if (courseData.subjectId) {
                this.form.subjectId = courseData.subjectId;
                console.log('通过API查询到课程对应的科目ID:', courseData.subjectId);
              } else if (courseData.subject && courseData.subject.id) {
                this.form.subjectId = courseData.subject.id;
                console.log('通过API查询到课程对应的科目ID:', courseData.subject.id);
              }
            }
          }).catch(error => {
            console.error('查询课程详情失败:', error);
          });
        });
      },

      /** 调用API查询表单章节对应的课程 */
      queryFormCourseByChapterId(chapterId) {
        console.log('调用API查询表单章节对应的课程:', chapterId);

        import('@/api/ssh/chapter').then(module => {
          module.getChapter(chapterId).then(response => {
            if (response.code === 200 && response.data) {
              const chapterData = response.data;
              console.log('章节详情数据:', chapterData);

              if (chapterData.courseId) {
                this.form.courseId = chapterData.courseId;
                console.log('通过API查询到章节对应的课程ID:', chapterData.courseId);

                // 继续查询课程对应的科目
                this.getFormSubjectByCourseId(chapterData.courseId);
              } else if (chapterData.course && chapterData.course.id) {
                this.form.courseId = chapterData.course.id;
                console.log('通过API查询到章节对应的课程ID:', chapterData.course.id);

                // 继续查询课程对应的科目
                this.getFormSubjectByCourseId(chapterData.course.id);
              }
            }
          }).catch(error => {
            console.error('查询章节详情失败:', error);
          });
        });
      },

      /** 题库类型变化处理 */
      handleFormTypeChange(type) {
        console.log('表单题库类型变化:', type);

        // 如果题库类型不是"OFFICIAL"，清空课程和章节选择
        if (type !== 'OFFICIAL') {
          this.form.courseId = null;
          this.form.chapterId = null;
          console.log('非OFFICIAL类型，已清空课程和章节选择');
        }
      }
  }
}
</script>

<style scoped>
.question-content {
  max-height: 80px;
  overflow: hidden;
  text-overflow: ellipsis;
  line-height: 1.4;
  word-break: break-all;
}

.difficulty-text {
  margin-left: 8px;
  font-size: 12px;
  color: #666;
}

.el-rate {
  display: inline-block;
}

/* 题库信息展示区域样式 */
.question-bank-info {
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 6px;
  padding: 20px;
  margin-bottom: 20px;
}

.info-item {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.info-item label {
  font-weight: 600;
  color: #495057;
  min-width: 80px;
  margin-right: 10px;
}

.info-value {
  color: #212529;
  font-size: 14px;
}

/* 题目列表区域样式 */
.question-list-section {
  margin-top: 20px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #495057;
  margin-bottom: 15px;
  padding-bottom: 8px;
  border-bottom: 2px solid #007bff;
}

.question-actions {
  margin-top: 20px;
  text-align: right;
}

.question-actions .el-button {
  margin-left: 10px;
}

.no-image {
  color: #909399;
  font-size: 12px;
  font-style: italic;
}

/* 题目选项管理弹出框样式 */
.el-dialog__body {
  padding: 20px;
}

.el-form-item__label {
  font-weight: 600;
  color: #303133;
}

.el-form-item__label::before {
  content: "";
  color: #f56c6c;
  margin-right: 4px;
}

.el-form-item__label[for*="optionA"]::before,
.el-form-item__label[for*="optionB"]::before,
.el-form-item__label[for*="optionC"]::before,
.el-form-item__label[for*="optionD"]::before,
.el-form-item__label[for*="correctOptions"]::before {
  content: "*";
  color: #f56c6c;
  margin-right: 4px;
}

/* 图片上传组件样式 */
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 148px;
  height: 148px;
  line-height: 148px;
  text-align: center;
}

.avatar {
  width: 148px;
  height: 148px;
  display: block;
  object-fit: cover;
}


</style>
